local skel = fk.CreateSkill {
  name = "lb_zero__tingyi",
  tags = { Skill.Combo },
  dynamic_desc = function(self, player, lang)
    local combo_list = table.simpleClone(player:getTableMark("@[lb_zero__tingyi]lb_zero__tingyi").combo_list or {})
    if #combo_list > 0 then
      return "lb_zero__tingyi_inder:" .. table.concat(table.map(combo_list, function(val)
        return Fk:translate(val)
      end), "+")
    end
    return "lb_zero__tingyi"
  end,
}

Fk:loadTranslationTable {
  ["lb_zero__tingyi"] = "霆毅",
  [":lb_zero__tingyi"] =
      "<b><a href='#ComboSkill-href'>连招技</a></b>（基本牌+锦囊牌+装备牌），你可以从弃牌堆获得一张雷【杀】或防具牌。" ..
      "当距离1以内的角色需要响应连招条件中的同名伤害牌时，你可以弃置手牌中的一张同名牌或防具牌以令其视为响应之。",

  [":lb_zero__tingyi_inder"] = "<b><a href='#ComboSkill-href'>连招技</a></b>（{1}），你可以从弃牌堆获得一张雷【杀】或防具牌。" ..
      "当距离1以内的角色需要响应连招条件中的同名伤害牌时，你可以弃置手牌中的一张同名牌或防具牌以令其视为响应之。",

  ["@[lb_zero__tingyi]lb_zero__tingyi"] = "霆毅",

  ["#lb_zero__tingyi"] = "霆毅：你可以从弃牌堆获得一张雷【杀】或防具牌",
  --["#lb_zero__tingyi-ask"] = "霆毅：你可以将一张 %arg 当【杀】或【闪】使用或打出",
  ["#lb_zero__tingyi-ask"] = "霆毅：你可以将弃置一张手牌中的 %arg2 或防具牌，令%src 视为响应 %arg",
  ["#lb_zero__tingyi-slash"] = "霆毅：请视为使用【杀】，以响应 %arg",

  ["$lb_zero__tingyi1"] = "统统接受制裁！",
  ["$lb_zero__tingyi2"] = "这些罪行，不可饶恕！",
  ["$lb_zero__tingyi3"] = "准备好，接受审判！",
}

local function utf8sub(str, startChar, numChars)
  local startIndex = 1
  while startChar > 1 do
    local char = string.byte(str, startIndex)
    startIndex = startIndex + (char > 240 and 4 or char > 225 and 3 or char > 192 and 2 or 1)
    startChar = startChar - 1
  end
  local currentIndex = startIndex
  while numChars > 0 and currentIndex <= #str do
    local char = string.byte(str, currentIndex)
    currentIndex = currentIndex + (char > 240 and 4 or char > 225 and 3 or char > 192 and 2 or 1)
    numChars = numChars - 1
  end
  return str:sub(startIndex, currentIndex - 1)
end

Fk:addQmlMark {
  name = skel.name,
  how_to_show = function(_, value, player)
    if type(value) == "table" then
      if type(value.combo_list) == "table" and #value.combo_list > 0 then
        local mark = {}
        for i, val in ipairs(value.combo_list) do
          local name = Fk:translate(val)
          name = utf8sub(name, 1, 2)
          if type(value.combo) == "table" then
            local combo = value.combo[i]
            if combo then
              local color = "yellow"
              if (combo == val or (Fk.all_card_types[combo] and Fk.all_card_types[combo]:getTypeString() == val)) then
                color = "green"
              end
              name = "<font color='" .. color .. "'>" .. name .. "</font>"
            end
          end
          table.insert(mark, name)
        end
        if #mark > 0 then
          return table.concat(mark, "/")
        end
      end
    end
    return " "
  end,
  ---[[
  qml_data = function(_, value, player)
    return value.combo
  end,
  qml_path = function(name, value, player)
    return (type(value.combo) == "table" and #value.combo > 0) and "packages/utility/qml/ViewPile" or ""
  end,
  --]]
}

skel:addEffect(fk.CardUsing, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(skel.name)
        and data.extra_data and data.extra_data.combo_skill and data.extra_data.combo_skill[skel.name]
        and table.find(player.room.discard_pile, function(id)
          local card = Fk:getCardById(id)
          return card.name == "thunder__slash" or card.sub_type == Card.SubtypeArmor
        end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local ids = table.filter(room.discard_pile, function(id)
      local card = Fk:getCardById(id)
      return card.name == "thunder__slash" or card.sub_type == Card.SubtypeArmor
    end)
    if #ids == 0 then return end
    local cards = room:askToCards(player, {
      min_num = 1,
      max_num = 1,
      pattern = tostring(Exppattern { id = ids }),
      skill_name = skel.name,
      expand_pile = ids,
      cancelable = true,
      prompt = "#lb_zero__tingyi"
    })
    if #cards > 0 then
      event:setCostData(self, { cards = cards })
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local list = player:getTableMark("@[lb_zero__tingyi]lb_zero__tingyi")
    list.combo = {}
    room:setPlayerMark(player, "@[lb_zero__tingyi]lb_zero__tingyi", list)
    local cards = event:getCostData(self).cards
    room:obtainCard(player, cards, true, fk.ReasonJustMove, player, skel.name)
  end,
})

skel:addEffect(fk.AfterCardUseDeclared, {
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(skel.name, true)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local list = player:getTableMark("@[lb_zero__tingyi]lb_zero__tingyi")
    local combo = list.combo or {}
    local combo_list = list.combo_list or {}
    table.insert(combo, data.card.trueName)
    while #combo > #combo_list do
      table.remove(combo, 1)
    end
    --[[
    if table.contains({"basic", "trick", "equip"}, combo_list[#combo]) then
      combo[#combo] = data.card:getTypeString()
    end
    --]]
    list.combo = combo
    if #combo == #combo_list and table.every(combo, function(element, index, array)
          return element == combo_list[index] or
              (Fk.all_card_types[element] and Fk.all_card_types[element]:getTypeString() == combo_list[index])
        end) then
      data.extra_data = data.extra_data or {}
      data.extra_data.combo_skill = data.extra_data.combo_skill or {}
      data.extra_data.combo_skill[skel.name] = true
    end
    room:setPlayerMark(player, "@[lb_zero__tingyi]lb_zero__tingyi", list)
  end,
})
--[[
skel:addEffect("viewas", {
  anim_type = "defensive",
  pattern = "slash,jink",
  prompt = function(self, player, selected_cards, selected)
    return "#lb_zero__tingyi-ask:::" .. player:getMark("lb_zero__tingyi_activated")
  end,
  interaction = function(self, player)
    local names = player:getViewAsCardNames(skel.name, { "slash", "jink" })
    return UI.CardNameBox { choices = names, all_choices = { "slash", "jink" } }
  end,
  filter_pattern = function(self, player, card_name, selected)
    return {
      min_num = 1,
      max_num = 1,
      pattern = player:getMark("lb_zero__tingyi_activated"),
    }
  end,
  view_as = function(self, player, cards)
    if not self.interaction.data or #cards ~= 1 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = skel.name
    card:addSubcards(cards)
    return card
  end,
  enabled_at_play = function(self, player)
    return not player:isNude() and player:getMark("lb_zero__tingyi_activated") ~= 0
  end,
  enabled_at_response = function(self, player, response)
    return not player:isNude() and player:getMark("lb_zero__tingyi_activated") ~= 0
  end,
})

skel:addEffect(fk.HandleAskForPlayCard, {
  can_refresh = function(self, event, target, player, data)
    if data.afterRequest and (data.extra_data or {}).lb_zero__tingyi_effected then
      return player:getMark("lb_zero__tingyi_activated") ~= 0
    end
    local combo_list = player:getTableMark("@[lb_zero__tingyi]lb_zero__tingyi").combo_list or {}
    return player:hasSkill(skel.name) and data.eventData
    and data.eventData.card and table.contains(combo_list, data.eventData.card.trueName)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if data.afterRequest then
      room:setPlayerMark(player, "lb_zero__tingyi_activated", 0)
    else
      room:setPlayerMark(player, "lb_zero__tingyi_activated", data.eventData.card.trueName)
      data.extra_data = data.extra_data or {}
      data.extra_data.lb_zero__tingyi_effected = true
    end
  end,
})
--]]


local tingyi_spec = {
  anim_type = "support",
  can_trigger = function(self, event, target, player, data)
    local combo_list = player:getTableMark("@[lb_zero__tingyi]lb_zero__tingyi").combo_list or {}
    return player:hasSkill(skel.name) and not player:isKongcheng() and player:distanceTo(target) <= 1
        and (data.extraData == nil or data.extraData.lb_zero__tingyi_ask == nil)
        and data.eventData and data.eventData.card and data.eventData.card.is_damage_card
        and table.contains(combo_list, data.eventData.card.trueName)
        and Exppattern:Parse(data.pattern):matchExp("slash,jink")
        and (event ~= fk.AskForCardUse
          or not Exppattern:Parse(data.pattern):matchExp("slash")
          or table.find(player.room.alive_players, function(to)
            return target:canUseTo(Fk:cloneCard("slash"), to, data.extraData)
          end)) -- 没合法目标不询问
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local card = data.eventData.card
    local cards = room:askToDiscard(player, {
      min_num = 1,
      max_num = 1,
      skill_name = skel.name,
      prompt = "#lb_zero__tingyi-ask:" .. target.id .. "::" .. card:toLogString() .. ":" .. card.trueName,
      cancelable = true,
      skip = true,
      include_equip = false,
      pattern = card.trueName .. "|.|.|.|.|armor",
    })
    if #cards > 0 then
      event:setCostData(self, { cards = cards })
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player:addSkillBranchUseHistory(skel.name, tostring(target.id))
    local room = player.room
    local cards = event:getCostData(self).cards
    room:throwCard(cards, skel.name, player)
    if target.dead then return end
    local name = "slash"
    if Exppattern:Parse(data.pattern):matchExp("slash") then
      if event == fk.AskForCardUse then
        local extraData = table.simpleClone(data.extraData)
        extraData.lb_zero__tingyi_ask = true
        local use = room:askToUseVirtualCard(target, {
          name = "slash",
          skill_name = skel.name,
          prompt = "#lb_zero__tingyi-slash:::" .. data.eventData.card:toLogString(),
          cancelable = false,
          skip = true,
          extra_data = extraData,
          event_data = data.eventData,
        })
        if use then
          data.result = use
          return true
        end
      end
    else
      name = "jink"
    end
    data.result = {
      from = target,
      card = Fk:cloneCard(name),
      tos = {},
    }
    return true
  end,
}

skel:addEffect(fk.AskForCardUse, tingyi_spec)
skel:addEffect(fk.AskForCardResponse, tingyi_spec)


skel:addAcquireEffect(function(self, player, is_start)
  player.room:setPlayerMark(player, "@[lb_zero__tingyi]lb_zero__tingyi", {
    combo_list = { "basic", "trick", "equip" }
  })
end)

skel:addLoseEffect(function(self, player, is_death)
  player.room:setPlayerMark(player, "@[lb_zero__tingyi]lb_zero__tingyi", 0)
  --player.room:setPlayerMark(player, "lb_zero__tingyi_activated", 0)
end)

return skel
